<script setup>
import { ref } from "vue";
import { invoke } from "@tauri-apps/api/tauri";
import { ElNotification } from 'element-plus'
import * as XLSX from 'xlsx';

let loading = ref(false);
const tableData = ref([]);
const month_df_Data = ref([]);

let screenHeight = ref(window.innerHeight - 60);

// 动态生成的列数组
const columns = ref([]);
const month_columns = ref([]);

async function greet() {
  loading.value = true;
  tableData.value = [];
  columns.value = [];
  month_columns.value = [];
  await invoke("greet").then(result => {
    if (result.startsWith("错误")) {
      loading.value = false;
      alert(result);
      return;
    }
    let obj=JSON.parse(result);
    month_df_Data.value = JSON.parse(obj.month_df);
    tableData.value = JSON.parse(obj.dfs);

    generateColumns();
    month_df_DataColumns();
    loading.value = false;
  }).catch(e => {
    loading.value = false;
    alert(e);
  });
}



// 获取 tableData 的第一行数据的键名和值
function generateColumns() {
  if (tableData.value.length > 0) {
    const firstRow = tableData.value[0];
    columns.value = Object.keys(firstRow).map(key => ({
      prop: key,
      label: key.charAt(0).toUpperCase() + key.slice(1)
    }));
  }
}

function month_df_DataColumns() {
  if (month_df_Data.value.length > 0) {
    const firstRow = month_df_Data.value[0];
    month_columns.value = Object.keys(firstRow).map(key => ({
      prop: key,
      label: key.charAt(0).toUpperCase() + key.slice(1)
    }));
  }
}


// 导出excel
const exportExcel = async (nums) => {

    if (nums == 1) {
    if (tableData.value.length == 0) {
      ElNotification({
        title: 'Error',
        message: '没有数据',
        type: 'error',
      });
      return;
    }
  } else if (nums == 2) {
    if (month_df_Data.value.length == 0) {
      ElNotification({
        title: 'Error',
        message: '没有月货量数据',
        type: 'error',
      });
      return;
    }
  }

  const ws = XLSX.utils.json_to_sheet(nums == 1? tableData.value : month_df_Data.value); // 将数据转换为工作表
  const wb = { Sheets: { 'Data': ws }, SheetNames: ['Data'] }; // 创建工作簿
  const excelBuffer = XLSX.write(wb, { bookType: 'xlsx', type: 'array' }); // 将工作簿转化为二进制缓冲区

  // 创建Blob对象并使用URL.createObjectURL方法生成URL
  const data = new Blob([excelBuffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8' });
  const url = URL.createObjectURL(data);

  // 创建隐藏的可下载链接
  const link = document.createElement('a');
  link.href = url;
  link.style.display = 'none';
  link.download = 'data.xlsx'; // 设置下载文件名
  document.body.appendChild(link);

  // 触发点击下载
  link.click();
  // 清理
  setTimeout(() => {
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);
  }, 100);
}



// // 导出excel
// const exportExcel = async (nums) => {
//   if (nums == 1) {
//     if (tableData.value.length == 0) {
//       ElNotification({
//         title: 'Error',
//         message: '没有数据',
//         type: 'error',
//       });
//       return;
//     }
//   } else if (nums == 2) {
//     if (c_class_Data.value.length == 0) {
//       ElNotification({
//         title: 'Error',
//         message: '没有C类数据',
//         type: 'error',
//       });
//       return;
//     }
//   }

//   const ws = XLSX.utils.json_to_sheet(nums == 1? tableData.value : c_class_Data.value); // 将数据转换为工作表
//   const wb = { Sheets: { 'Data': ws }, SheetNames: ['Data'] }; // 创建工作簿
//   const excelBuffer = XLSX.write(wb, { bookType: 'xlsx', type: 'array' }); // 将工作簿转化为二进制缓冲区

//   // 创建Blob对象并将其转换为base64
//   const data = new Blob([excelBuffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8' });
//   const reader = new FileReader();
//   reader.readAsDataURL(data);
//   reader.onload = async () => {
//     const base64Data = reader.result.split(',')[1];
//     // 调用Tauri后端命令保存文件
//     await invoke('save_file', { base64Data });
//   };
// }



window.addEventListener('resize', function () {
  screenHeight.value = window.innerHeight - 60;
  console.log('Screen height:', screenHeight);
});

</script>

<template>
  <dev class="container">
    <dev class="header">
      <el-button type="primary" :loading="loading" @click="greet"
        style="margin-left: 10px;margin-top: 10px;">保税坏件货量计算</el-button>
      <el-button type="success" @click="exportExcel(1)" style="margin-top: 10px;">导出Excel</el-button>
      <el-button type="danger" @click="exportExcel(2)" style="margin-top: 10px;">导出月货量</el-button>
    </dev>

    <dev class="content">
     <dev class="left_table">
      <el-scrollbar :height="screenHeight">
        <el-table :data="tableData" :height="screenHeight" stripe style="width: 100%">
          <el-table-column type="index" label="序号" width="80" />
          <!-- 动态生成的列 -->
          <template v-for="(column, index) in columns" :key="index">
            <el-table-column :prop="column.prop" :label="column.label" />
          </template>
        </el-table>
      </el-scrollbar>
     </dev>

     <dev class="right_table">
      <el-scrollbar :height="screenHeight">
        <el-table :data="month_df_Data" :height="screenHeight" stripe style="width: 100%">
          <el-table-column type="index" label="序号" width="80" />
          <!-- 动态生成的列 -->
          <template v-for="(column, index) in month_columns" :key="index">
            <el-table-column :prop="column.prop" :label="column.label" />
          </template>
        </el-table>
      </el-scrollbar>
     </dev>
    </dev>
  </dev>
</template>

<style scoped>
.container {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.header {
  flex: 1;
}

.content {
  flex: 18;
  display: flex;
}

.left_table {
  flex: 2;
}
.right_table {
  flex: 1;
}
</style>
